/*
 * Copyright 2006 Robert Burrell Donkin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package rat;

import java.io.File;
import java.io.IOException;

import rat.license.ILicense;
import rat.license.ILicenseMatcher;

/**
 * An element whose content is either known to be standard text
 * or who content is unknown.
 */
class StandardContentElement extends AbstractElement implements IWorker {
	
	private LicenseCheckWorker worker;
	private IOException error;
	private final ILicenseMatcher matcher;
	
	public StandardContentElement(File file, final ILicenseMatcher matcher) {
		super(file);
		this.matcher = matcher;
	}

	public void accept(IElementVisitor visitor) {
		visitor.visit(this);
	}

	public void work() {
		try {
			worker = new LicenseCheckWorker(getName(), getReader(), matcher);
			worker.read();
		} catch (IOException e) {
			error = e;
		}
	}
	
	public Exception getError() {
		Exception result = error;
		if (error == null && worker != null) {
			result = worker.getError();
		}
		return result;
	}
    
    /**
     * Gets license for the content.
     * @return <code>ILicense</code>, not null
     */
    public ILicense getLicense() {
        ILicense result = null;
        if (worker != null) {
            result = worker.getLicense();
        }
        return result;
    }
	
	/**
	 * Gets a sample of the violating document.
	 * @return a sample of the violation 
	 * or null if the document has no violation
	 */
	public String getViolationSample()
	{
		String result = null;
		if (worker != null)
		{
			if (error == null)
			{
				if (!worker.isLicenseApproved())
				{
					result = worker.getLicense().getNotes();
				}
			}
			else
			{
				result = error.toString();
			}
		}
		return result;
	}
	
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(' ');
		Exception error = getError();
		if (error != null) {
			buffer.append("*E     ");
			buffer.append(getName());
			buffer.append(error.toString());
		} else if (worker == null) {
			buffer.append(" S     ");
			buffer.append(getName());
		} else if (worker.isLicenseApproved()){
			buffer.append(" ");
            buffer.append(worker.getLicense().getCode());
            buffer.append(" ");
			buffer.append(getName());
		} else {
			buffer.append("!");
            buffer.append(worker.getLicense().getCode());
            buffer.append(" ");
			buffer.append(getName());
		}
			
		return buffer.toString();
	}
}
